package com.example.wuqujingdianphone.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.azhon.appupdate.config.UpdateConfiguration;
import com.azhon.appupdate.listener.OnButtonClickListener;
import com.azhon.appupdate.listener.OnDownloadListener;
import com.azhon.appupdate.manager.DownloadManager;
import com.example.wuqujingdianphone.MyApplication;
import com.example.wuqujingdianphone.R;
import com.example.wuqujingdianphone.api.GlobalConfig;
import com.example.wuqujingdianphone.base.BaseActivity;
import com.example.wuqujingdianphone.bean.BookHomeListBean;
import com.example.wuqujingdianphone.bean.UpdateBean;
import com.example.wuqujingdianphone.fragment.BRBookFragment;
import com.example.wuqujingdianphone.fragment.bookcity.BookCityHomeFragment;
import com.example.wuqujingdianphone.fragment.mainfragment.BookRackFragment;
import com.example.wuqujingdianphone.fragment.mainfragment.BookShopFragment;
import com.example.wuqujingdianphone.fragment.mainfragment.MyFragment;
import com.example.wuqujingdianphone.utils.AppManager;
import com.example.wuqujingdianphone.utils.FragmentTabUtils;
import com.example.wuqujingdianphone.utils.GsonUtil;
import com.example.wuqujingdianphone.utils.Message1Event;
import com.example.wuqujingdianphone.utils.SPUtil;
import com.example.wuqujingdianphone.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.http.POST;

public class MainActivity extends BaseActivity implements OnButtonClickListener, OnDownloadListener {
    private static final String TAG = "MainActivity";

    @BindView(R.id.content)
    FrameLayout content;

    @BindView(R.id.rb_book_rack)
    RadioButton mRbBookRack;
    @BindView(R.id.rb_book_shop)
    RadioButton mRbBookShop;
    @BindView(R.id.rb_my)
    RadioButton mRbMy;
    @BindView(R.id.rg_content_fragment)
    RadioGroup mRgContent;


    //上次按下返回键的系统时间
    private long lastBackTime = 0;
    //当前按下返回键的系统时间
    private long currentBackTime = 0;

    private boolean isLogin;

    private FragmentTabUtils fragmentTabUtils;
    private int currentTabIndex;
    private FragmentManager fm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main1);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initFragmentTabUtils();
        checkUpdate();
    }

    private void initFragmentTabUtils() {
        ArrayList<Fragment> fragments = new ArrayList<>();
        fragments.add(BRBookFragment.getBRBookFragment());
        fragments.add(BookCityHomeFragment.getBookCityHomeFragment());
        fragments.add(MyFragment.getMyFragment());
        fragmentTabUtils = new FragmentTabUtils(getSupportFragmentManager(), fragments, R.id.content, mRgContent);
        fragmentTabUtils.setOnRgsExtraCheckedChangedListener(new FragmentTabUtils.OnRgsExtraCheckedChangedListener() {
            @Override
            public void OnRgsExtraCheckedChanged(RadioGroup radioGroup, int checkedId, int index) {
                currentTabIndex = index;
            }
        });
        checkUpdate();
    }

    private void checkUpdate() {
        OkGo.<String>get("http://service.wenqujingdian.com/wqjd/app/GetTheCurrentVersionOfApp")
                .tag(this)
                .params("appId", "android")
                .params("appType", "android")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String ds = response.body();
                        UpdateBean updateBean = GsonUtil.GsonToBean(response.body(), UpdateBean.class);
//                        String apkUrl = updateBean.getData().getAppDownloadUrl();
                        String apkUrl = "http://hxgd.zicp.net:90/apk/yuemeishiguang.apk";
                        String appversion = updateBean.getData().getAppVersion();
                        String versiondate = updateBean.getData().getVersionDate();
                        boolean isForced = updateBean.getData().isIsForced();
                        String versiondescribe = updateBean.getData().getVersionDescribe();
                        int gradleVersion = updateBean.getData().getGradleVersion();
                        startUpdate(gradleVersion, isForced, apkUrl, versiondescribe);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtil.show("更新检测失败");
                    }
                });
    }

    private void startUpdate(int versionCode, boolean isForced, String apkurl, String apkDec) {
        /*
         * 整个库允许配置的内容
         * 非必选
         */
        UpdateConfiguration configuration = new UpdateConfiguration()
                //输出错误日志
                .setEnableLog(true)
                //设置自定义的下载
                //.setHttpManager()
                //下载完成自动跳动安装页面
                .setJumpInstallPage(true)
                //设置对话框背景图片 (图片规范参照demo中的示例图)
                //.setDialogImage(R.drawable.ic_dialog)
                //设置按钮的颜色
                //.setDialogButtonColor(Color.parseColor("#E743DA"))
                //设置按钮的文字颜色
                .setDialogButtonTextColor(Color.WHITE)
                //支持断点下载
                .setBreakpointDownload(true)
                //设置是否显示通知栏进度
                .setShowNotification(true)
                //设置强制更新
                .setForcedUpgrade(isForced)
                //设置对话框按钮的点击监听
                .setButtonClickListener(this)
                //设置下载过程的监听
                .setOnDownloadListener(this);

        DownloadManager manager = DownloadManager.getInstance(this);
        manager.setApkName("yuemeishiguang.apk")
                .setApkUrl(apkurl)
                .setSmallIcon(R.drawable.logo_01)
                .setShowNewerToast(false)
                .setConfiguration(configuration)
//                .setDownloadPath(Environment.getExternalStorageDirectory() + "/AppUpdate")
                .setApkVersionCode(versionCode)
                //.setApkVersionName("2.1.8")
                //.setApkSize("20.4")
                .setAuthorities(getPackageName())
                .setApkDescription(apkDec)
                .download();
    }


//    /**
//     * 设置默认的
//     */
//    private void setDefaultFragment() {
//        fm = getSupportFragmentManager();
//        mRbBookShop.setChecked(true);
//    }

//    @Override
//    public void onCheckedChanged(RadioGroup group, int checkedId) {
//        isLogin = SPUtil.getBoolean(this, "isLogin", false);
//        switch (checkedId) {
//            case R.id.rb_book_rack:
//                if (!isLogin) {
//                    startActivityForResult(new Intent(this, LoginActivity.class), 3);
//                } else {
//                    switchFragment(BookRackFragment.getBookRackFragment());
//                }
//                break;
//            case R.id.rb_book_shop:
////                switchFragment(BookShopFragment.getBookShopFragment());
//                switchFragment(BookCityHomeFragment.getBookCityHomeFragment());
//                break;
//            case R.id.rb_my:
//                if (!isLogin) {
//                    startActivityForResult(new Intent(this, LoginActivity.class), 4);
//                } else {
//                    switchFragment(MyFragment.getMyFragment());
//                }
//                break;
//        }
//    }

//    private void switchFragment(Fragment fragment) {
//        FragmentTransaction ft = fm.beginTransaction();
//        ft.replace(R.id.content, fragment);
//        ft.commit();
//    }

    @Override
    protected void onNewIntent(Intent intent) {
        if (MyApplication.flagShujia) {
            if (intent.getBooleanExtra("shujia", true)) {
                View button = mRgContent.getChildAt(0);
                if (button instanceof RadioButton) {
                    ((RadioButton) button).setChecked(true);
                }
            }
            MyApplication.flagShujia = false;
        }

        if (MyApplication.flagMine) {
            if (intent.getBooleanExtra("mine", true)) {
                View button = mRgContent.getChildAt(2);
                if (button instanceof RadioButton) {
                    ((RadioButton) button).setChecked(true);
                }
            }
            MyApplication.flagMine = false;
        }
    }

    private long oneTime = 0;

    /**
     * 点击两次退出程序
     */
    @Override
    public void onBackPressed() {
        long twoTime = System.currentTimeMillis();
        if (twoTime - oneTime > 2000) {
            ToastUtil.showToast(getResources().getString(R.string.exit_tips));
            oneTime = twoTime;
        } else {
            AppManager.getAppManager().AppExit(MyApplication.mContext);
        }
    }


    @Override
    public void onButtonClick(int id) {

    }

    @Override
    public void start() {

    }

    @Override
    public void downloading(int max, int progress) {

    }

    @Override
    public void done(File apk) {

    }

    @Override
    public void error(Exception e) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMsgEvent(Message1Event messageEvent) {
        String msg = messageEvent.getMsg();
        if (msg.equals(GlobalConfig.LOGIN_IS_OK)) {
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
